#!/usr/bin/env bash
# GitDiagram 完整启动脚本 - 适用于无代码情况

# 颜色代码
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # 重置颜色

echo -e "${BLUE}===== GitDiagram 一键部署工具 =====${NC}"
echo -e "${YELLOW}此脚本将从GitHub下载GitDiagram并启动完整环境${NC}"

# 检查Docker是否已安装
if ! [ -x "$(command -v docker)" ]; then
  echo -e "${RED}错误：Docker未安装。请先安装Docker。${NC}"
  echo -e "安装指南: https://docs.docker.com/engine/install/"
  exit 1
fi

# 检查Git是否已安装
if ! [ -x "$(command -v git)" ]; then
  echo -e "${RED}错误：Git未安装。请先安装Git。${NC}"
  echo -e "安装指南: https://git-scm.com/downloads"
  exit 1
fi

# 检查docker-compose命令
if ! [ -x "$(command -v docker-compose)" ]; then
  echo -e "${YELLOW}警告：未检测到docker-compose命令，尝试使用docker compose...${NC}"
  COMPOSE_CMD="docker compose"
else
  COMPOSE_CMD="docker-compose"
fi

# 创建临时工作目录
WORK_DIR="gitdiagram-docker"
if [ -d "$WORK_DIR" ]; then
  echo -e "${YELLOW}目录 $WORK_DIR 已存在。是否删除现有目录并重新下载? [y/N]${NC}"
  read -r response
  if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
    rm -rf "$WORK_DIR"
  else
    echo -e "${GREEN}将使用现有目录${NC}"
    cd "$WORK_DIR" || exit 1
    if [ -f "docker-compose.dev.yml" ]; then
      echo -e "${GREEN}找到docker-compose.dev.yml，跳过下载步骤${NC}"
      goto_start=true
    fi
  fi
fi

if [ "$goto_start" != "true" ]; then
  echo -e "${BLUE}克隆GitDiagram代码...${NC}"
  git clone https://github.com/ahmedkhaleel2004/gitdiagram.git "$WORK_DIR"
  cd "$WORK_DIR" || exit 1
  
  # 创建Docker部署文件
  echo -e "${BLUE}创建Docker部署文件...${NC}"
  
  # 创建docker-compose.dev.yml
  cat > docker-compose.dev.yml << 'EOL'
version: '3.8'

services:
  # 前端服务
  frontend:
    build:
      context: .
      dockerfile: Dockerfile.frontend
    ports:
      - "3000:3000"
    volumes:
      - ./src:/app/src
      - ./public:/app/public
    environment:
      - NEXT_PUBLIC_API_DEV_URL=http://api:8000
    depends_on:
      - api
    restart: unless-stopped

  # 后端API服务
  api:
    build: 
      context: ./backend
      dockerfile: Dockerfile
    ports:
      - "8000:8000"
    volumes:
      - ./backend:/app
    env_file:
      - .env
    environment:
      - ENVIRONMENT=${ENVIRONMENT:-development}
      - POSTGRES_URL=postgresql://postgres:${DB_PASSWORD:-postgres}@db:5432/gitdiagram
    depends_on:
      - db
    dns:
      - 8.8.8.8
      - 8.8.4.4
    restart: unless-stopped

  # 数据库服务
  db:
    image: postgres:15-alpine
    ports:
      - "5432:5432"
    volumes:
      - gitdiagram_data:/var/lib/postgresql/data
    environment:
      - POSTGRES_PASSWORD=${DB_PASSWORD:-postgres}
      - POSTGRES_USER=postgres
      - POSTGRES_DB=gitdiagram
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

volumes:
  gitdiagram_data:
    driver: local
EOL

  # 创建Dockerfile.frontend
  cat > Dockerfile.frontend << 'EOL'
FROM node:20-alpine

# 设置工作目录
WORKDIR /app

# 安装pnpm
RUN npm install -g pnpm

# 复制package.json和pnpm-lock.yaml
COPY package.json pnpm-lock.yaml ./

# 安装依赖
RUN pnpm install

# 复制其余文件
COPY . .

# 构建应用
RUN pnpm build

# 暴露端口
EXPOSE 3000

# 启动命令
CMD ["pnpm", "start"]
EOL
fi

# 检查.env文件
if [ ! -f ".env" ]; then
  echo -e "${YELLOW}未找到.env文件，将从.env.example创建${NC}"
  if [ -f ".env.example" ]; then
    cp .env.example .env
  else
    # 创建基本的.env文件
    cat > .env << 'EOL'
# 数据库配置
POSTGRES_URL=postgresql://postgres:postgres@db:5432/gitdiagram
DB_PASSWORD=postgres

# OpenAI配置
OPENAI_API_KEY=

# 启用HTTPS和API密钥检查
ENABLE_HTTPS=false
ENABLE_API_KEY=false

# 环境设置
ENVIRONMENT=development
EOL
  fi
  echo -e "${GREEN}.env文件已创建${NC}"
  echo -e "${YELLOW}请编辑.env文件添加您的OpenAI API密钥${NC}"
  echo -e "${YELLOW}是否需要编辑.env文件? [y/N]${NC}"
  read -r response
  if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
    if [ -x "$(command -v nano)" ]; then
      nano .env
    elif [ -x "$(command -v vim)" ]; then
      vim .env
    else
      echo -e "${YELLOW}未找到编辑器，请稍后手动编辑.env文件${NC}"
    fi
  fi
fi

# 检查数据库密码
DB_PASSWORD=$(grep -o "DB_PASSWORD=.*" .env | cut -d= -f2 || echo "")
if [ -z "$DB_PASSWORD" ]; then
  # 生成随机密码并添加到.env
  RANDOM_PASSWORD=$(openssl rand -base64 12 | tr -dc 'a-zA-Z0-9' | head -c 12 || echo "postgres")
  echo "DB_PASSWORD=$RANDOM_PASSWORD" >> .env
  echo -e "${GREEN}已生成随机数据库密码并添加到.env${NC}"
fi

# 构建并启动容器
echo -e "${BLUE}启动GitDiagram服务...${NC}"
$COMPOSE_CMD -f docker-compose.dev.yml up -d

# 检查服务状态
echo -e "${BLUE}检查服务状态...${NC}"
sleep 5

if $COMPOSE_CMD -f docker-compose.dev.yml ps | grep -q "Up"; then
  echo -e "${GREEN}GitDiagram服务已成功启动！${NC}"
  echo -e "${GREEN}前端地址: http://localhost:3000${NC}"
  echo -e "${GREEN}后端API地址: http://localhost:8000${NC}"
  echo -e "${YELLOW}首次启动可能需要一些时间加载，请耐心等待${NC}"
  echo -e "${BLUE}查看日志: $COMPOSE_CMD -f docker-compose.dev.yml logs -f${NC}"
else
  echo -e "${RED}服务启动可能出现问题，请检查日志:${NC}"
  echo -e "${BLUE}$COMPOSE_CMD -f docker-compose.dev.yml logs${NC}"
fi

echo -e "${YELLOW}后续使用说明:${NC}"
echo -e "${GREEN}1. 停止服务: $COMPOSE_CMD -f docker-compose.dev.yml down${NC}"
echo -e "${GREEN}2. 重启服务: $COMPOSE_CMD -f docker-compose.dev.yml up -d${NC}"
echo -e "${GREEN}3. 查看日志: $COMPOSE_CMD -f docker-compose.dev.yml logs -f${NC}"
echo -e "${GREEN}4. 项目目录: $(pwd)${NC}" 